package com.comm;

import com.dao.IMyuser;
import com.model.MyUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Order(3)
@Component
@Aspect
public class LogAopAspect {
    @Autowired
    private IMyuser iMyuser;

    @Around("@annotation(com.comm.LogAnno)")
    public Object auoundAd(ProceedingJoinPoint pjp){
        System.out.println("进入环形通知方法");

        //获取方法签名
        MethodSignature methodSignature=(MethodSignature) pjp.getSignature();

        //获取方法
        Method method=methodSignature.getMethod();

//        //获取方法上面的注解
//        LogAnno logAnno=method.getAnnotation(LogAnno.class);
//        String oper=logAnno.OperateType();

        //setIp 获取访问接口时的各种操作
        MyUser myUser=new MyUser();
//        sysLog.setUsername("admin");
//        sysLog.setOperation("接口描述"+oper);
        myUser.setIp(HttpContextUtil.getIPAddress());

        //setMethod  请求方法当中的类
        String className=pjp.getTarget().getClass().getName();
        String methodName=methodSignature.getName();
        myUser.setMethod(className+"."+methodName);

        //请求方法的相关参数
        Object[] args=pjp.getArgs();
        System.out.println("获取参数的长度："+args.length);
        LocalVariableTableParameterNameDiscoverer u=new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames=u.getParameterNames(method);
        System.out.println("方法当中所涵盖的参数名称："+paramNames.length);
        if(args!=null && paramNames!=null){
            String params="";
            for(int i=0;i<args.length;i++){
                params+=" "+paramNames[i]+":"+args[i];
            }
//            myUser.setParams(params);
        }

        Object result=null;
        try{
            try{
                result=pjp.proceed();
            }catch (Throwable e){
                e.printStackTrace();
            }
        }catch(Exception e){
             e.printStackTrace();
        }finally {
            iMyuser.insertLog(myUser);
            System.out.println("将访问接口的信息记录到数据库中");
        }
        System.out.println("结束环形通知方法");
        return result;
    }
}
